<template>
    <div class="button-container">
        <el-button type="primary" @click="openDialog"> 新增图书 </el-button>
    </div>
    <div class="font-size-controls">
        <el-button @click="increaseFontSize">增大字号 +</el-button>
        <el-button @click="decreaseFontSize">减小字号 -</el-button>
        <el-button @click="resetFontSize">重置字号 reset</el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" title="新增图书" width="500px">
        <el-form ref="form" :model="form" label-position="right" label-width="100px" :rules="rules">
            <el-form-item label="书名" prop="bookname">
                <el-input v-model="form.bookname" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
                <el-input v-model="form.author" />
            </el-form-item>
            <el-form-item label="出版社" prop="publisher">
                <el-input v-model="form.publisher" />
            </el-form-item>
            <el-form-item label="类别" prop="category">
                <el-select v-model="form.category" placeholder="请选择类别" style="width: 100%">
                    <el-option label="文学" value="文学" />
                    <el-option label="科技" value="科技" />
                    <el-option label="历史" value="历史" />
                    <el-option label="艺术" value="艺术" />
                    <el-option label="哲学" value="哲学" />
                    <el-option label="经济" value="经济" />
                    <el-option label="教育" value="教育" />
                    <el-option label="医学" value="医学" />
                </el-select>
            </el-form-item>
            <el-form-item label="定价" prop="price">
                <el-input v-model.number="form.price" type="number" />
            </el-form-item>
            <el-form-item label="库存" prop="stock">
                <el-input v-model.number="form.stock" type="number" />
            </el-form-item>
            <el-form-item label="ISBN" prop="isbn">
                <el-input v-model="form.isbn" />
            </el-form-item>
            <el-form-item label="出版日期" prop="publishDate">
                <el-date-picker
                    v-model="form.publishDate"
                    type="date"
                    placeholder="选择出版日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
        </template>
    </el-dialog>

    <el-table :data="paginatedBooks" style="width: 100%" :row-class-name="getCategoryCellClass">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="书名" width="120" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="isbn" label="ISBN" width="120" />
        <el-table-column prop="publisher" label="出版社" width="120" />
        <el-table-column prop="publishDate" label="出版日期" width="120" />
        <el-table-column prop="price" label="定价" width="120">
            <template #default="scope">
                {{ scope.row.price }} 元
            </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="createdAt" label="创建时间" width="220" />
        <el-table-column prop="updatedAt" label="更新时间" width="220" />
        <el-table-column label="类别" width="120">
            <template #default="scope">
                <span :class="getCategoryClass(scope.row.category)">{{ scope.row.category }}</span>
            </template>
        </el-table-column>
        <el-table-column label="选项操作" min-width="100">
            <template #default="scope">
                <el-button link type="danger" size="small" @click.prevent="handleDelete(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <div class="pagination-container">
        <el-pagination 
            @current-change="handleCurrentChange" 
            :current-page="currentPage" 
            :page-size="pageSize"
            :total="books.length" 
            layout="prev, pager, next" 
            style="margin-top: 20px"
            v-if="books.length > 0" 
        />
        <div v-else style="text-align: center; margin-top: 20px">暂无数据</div>
    </div>

    <!-- 统计信息显示区域 -->
    <div class="stats-container" v-if="books.length > 0">
        <h3>图书统计信息</h3>
        <p>图书总数: {{ bookStats.totalBooks }}，平均价格: {{ bookStats.averagePrice.toFixed(2) }} 元</p>
        <p>分类统计:</p>
        <ul>
            <li v-for="(count, category) in bookStats.categoryCounts" :key="category">
                {{ category }}: {{ count }} 本
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            dialogFormVisible: false,
            paginatedBooks: [],
            currentPage: 1,
            pageSize: 10,
            books: [],
            form: {
                bookname: '',
                author: '',
                publisher: '',
                category: '',
                price: '',
                stock: 0,
                isbn: '',
                publishDate: ''
            },
            rules: {
                bookname: [{ required: true, message: '请输入书名', trigger: 'blur' }],
                author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
                publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
                category: [{ required: true, message: "请输入类别", trigger: "blur" }],
                price: [{ required: true, message: "请输入定价", trigger: "blur" }],
                stock: [{ required: true, message: "请输入库存", trigger: "blur" }]
            },
        };
    },
    methods: {
        openDialog() {
            this.dialogFormVisible = true;
        },
        handleDelete(id) {
            this.$confirm('确认删除该图书吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                this.books = this.books.filter(book => book.id !== id);
                this.updatePaginatedBooks();
                this.$message.success('删除成功');
            }).catch((error) => {
                if (error === 'cancel') {
                    this.$message.info('已取消删除');
                } else {
                    this.$message.error(`删除失败: ${error.message || '未知错误'}`);
                }
            });
        },
        generateUniqueId() {
            return Date.now().toString(36) + Math.random().toString(36).substring(2);
        },
        increaseFontSize() {
            const table = document.querySelector('.el-table');
            if (table) {
                const currentSize = parseFloat(window.getComputedStyle(table).fontSize) || 14;
                table.style.fontSize = `${currentSize + 1}px`;
            }
        },
        decreaseFontSize() {
            const table = document.querySelector('.el-table');
            if (table) {
                const currentSize = parseFloat(window.getComputedStyle(table).fontSize) || 14;
                table.style.fontSize = `${Math.max(currentSize - 1, 10)}px`;
            }
        },
        resetFontSize() {
            const table = document.querySelector('.el-table');
            if (table) {
                table.style.fontSize = '14px';
            }
        },
        getCategoryCellClass({ row }) {
            if (row.category === '文学') {
                return 'literature-cell';
            } else if (row.category === '科技') {
                return 'technology-cell';
            } else if (row.category === '历史') {
                return 'history-cell';
            }
            return '';
        },
        getCategoryClass(category) {
            const categoryClasses = {
                '文学': 'category-literature',
                '科技': 'category-technology', 
                '历史': 'category-history',
                '艺术': 'category-art',
                '哲学': 'category-philosophy',
                '经济': 'category-economics',
                '教育': 'category-education',
                '医学': 'category-medicine'
            };
            return categoryClasses[category] || 'category-default';
        },
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const newBook = {
                        id: this.generateUniqueId(),
                        title: this.form.bookname,
                        category: this.form.category,
                        author: this.form.author,
                        isbn: this.form.isbn,
                        publisher: this.form.publisher,
                        publishDate: this.form.publishDate,
                        price: parseFloat(this.form.price),
                        stock: parseInt(this.form.stock),
                        createdAt: new Date().toLocaleString(),
                        updatedAt: new Date().toLocaleString(),
                    };
                    console.log('提交的图书信息:', newBook);
                    this.books.unshift(newBook); // 添加到开头
                    this.$message.success('图书添加成功！');
                    this.dialogFormVisible = false;
                    this.resetForm();
                    this.updatePaginatedBooks();
                }
            });
        },
        resetForm() {
            this.form = {
                bookname: '',
                author: '',
                publisher: '',
                category: '',
                price: '',
                stock: 0,
                isbn: '',
                publishDate: ''
            };
            if (this.$refs.form) {
                this.$refs.form.clearValidate();
            }
        },
        handleCurrentChange(page) {
            this.currentPage = page;
            this.updatePaginatedBooks();
        },
        updatePaginatedBooks() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.paginatedBooks = this.books.slice(start, end);
        },
        loadBooksData() {
                fetch('/data/books.json')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            this.books = data;
            this.updatePaginatedBooks();
            console.log('图书数据加载成功');
        })
        .catch(error => {
            console.error('获取图书数据失败:', error);
            // 加载模拟数据作为备选
            this.loadMockData();
        });
}
    },
    mounted() {
        this.loadBooksData();
    },
    computed: {
        bookStats() {
            const stats = {
                totalBooks: this.books.length,
                categoryCounts: {},
                averagePrice: 0,
            };

            // 统计每种分类的数量
            this.books.forEach(book => {
                if (book.category) {
                    stats.categoryCounts[book.category] = (stats.categoryCounts[book.category] || 0) + 1;
                }
            });

            // 计算平均价格
            if (this.books.length > 0) {
                const totalPrice = this.books.reduce((sum, book) => sum + (parseFloat(book.price) || 0), 0);
                stats.averagePrice = totalPrice / this.books.length;
            }

            return stats;
        },
    },
};
</script>

<style scoped>
.button-container {
    margin-bottom: 20px;
}

.font-size-controls {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.stats-container {
    margin-top: 30px;
    padding: 20px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: #f9f9f9;
}

.stats-container h3 {
    margin-top: 0;
    color: #333;
}

.stats-container ul {
    margin: 10px 0;
    padding-left: 20px;
}

.stats-container li {
    margin: 5px 0;
}

/* 类别样式 */
.category-literature {
    color: #e74c3c;
    font-weight: bold;
}

.category-technology {
    color: #3498db;
    font-weight: bold;
}

.category-history {
    color: #9b59b6;
    font-weight: bold;
}

.category-art {
    color: #e67e22;
    font-weight: bold;
}

.category-philosophy {
    color: #34495e;
    font-weight: bold;
}

.category-economics {
    color: #27ae60;
    font-weight: bold;
}

.category-education {
    color: #16a085;
    font-weight: bold;
}

.category-medicine {
    color: #c0392b;
    font-weight: bold;
}

.category-default {
    color: #7f8c8d;
}

/* 行样式 */
.literature-cell {
    background-color: #fdedec;
}

.technology-cell {
    background-color: #ebf5fb;
}

.history-cell {
    background-color: #f4ecf7;
}
</style>